from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = '测试成绩预测功能'

    def add_arguments(self, parser):
        parser.add_argument(
            '--student-id',
            type=str,
            help='测试学生ID（如未提供则使用模拟数据）'
        )
        parser.add_argument(
            '--subject-id',
            type=int,
            help='测试科目ID（如未提供则使用模拟数据）'
        )

    def handle(self, *args, **options):
        self.stdout.write('=' * 50)
        self.stdout.write('🧪 测试成绩预测功能')
        self.stdout.write('=' * 50)

        try:
            from prediction.ml.predictors.score_predictor import ScorePredictor
            from prediction.ml.features.feature_engineer import FeatureEngineer

            # 创建预测器和特征工程器
            predictor = ScorePredictor()
            feature_engineer = FeatureEngineer()

            # 检查预测器状态
            model_info = predictor.get_model_info()
            self.stdout.write(f'📊 预测器状态: {model_info["status"]}')

            if not predictor.is_ready():
                self.stdout.write(
                    self.style.ERROR('❌ 预测器未就绪，请先训练模型')
                )
                return

            self.stdout.write(
                self.style.SUCCESS('✅ 预测器就绪，开始测试...')
            )

            # 测试用例
            test_cases = [
                {
                    'name': '优秀学生',
                    'scores': [95, 92, 98, 96, 94],
                    'full_score': 150
                },
                {
                    'name': '进步学生',
                    'scores': [70, 75, 80, 85, 88],
                    'full_score': 150
                },
                {
                    'name': '波动学生',
                    'scores': [90, 75, 95, 70, 92],
                    'full_score': 150
                },
                {
                    'name': '新生',
                    'scores': [],
                    'full_score': 150
                }
            ]

            for i, test_case in enumerate(test_cases, 1):
                self.stdout.write(f'\n📋 测试用例 {i}: {test_case["name"]}')
                self.stdout.write(f'   历史成绩: {test_case["scores"]}')

                # 计算特征
                student_data = {
                    'historical_scores': test_case['scores'],
                    'subject_full_score': test_case['full_score']
                }
                features = feature_engineer.extract_features(student_data)

                # 执行预测
                result = predictor.predict(features)

                if result['success']:
                    self.stdout.write(
                        self.style.SUCCESS(
                            f'   🎯 预测分数: {result["predicted_score"]:.1f}'
                        )
                    )
                    self.stdout.write(
                        f'   📊 置信度: {result["confidence"]:.2f}'
                    )
                    self.stdout.write(
                        f'   🔧 模型类型: {result["model_type"]}'
                    )
                else:
                    self.stdout.write(
                        self.style.WARNING(
                            f'   ⚠️ 预测失败: {result.get("error", "未知错误")}'
                        )
                    )
                    if result.get('fallback_to_rules'):
                        self.stdout.write(
                            self.style.WARNING('   🔄 已回退到规则预测')
                        )

            self.stdout.write('\n' + '=' * 50)
            self.stdout.write(
                self.style.SUCCESS('✅ 预测测试完成!')
            )

        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'❌ 测试失败: {e}')
            )
            import traceback
            self.stdout.write(traceback.format_exc())